<template>
    <canvas ref="refCanvas" class="chart-canvas" width="165" height="55" style="width:165px; height: 55px" :style="'border-color: '+props.color"></canvas>
</template>

<style scoped>
.chart-canvas {
    border: 1px solid;
    margin:5px;
}
</style>

<script lang="ts" setup>
import { onMounted, ref, Ref } from 'vue';
// import * as echarts from 'echarts'
// import { EChartsType } from 'echarts';

const refCanvas = ref(null) as unknown as Ref<HTMLCanvasElement>
let ctx: CanvasRenderingContext2D

const props = withDefaults(defineProps<{
    color: string
}>(), {
    color: 'green'
})

const MaxDataLen = 161
const data: number[] = [0]

onMounted(()=>{
    ctx = refCanvas.value.getContext("2d") as CanvasRenderingContext2D
})

function push(v:number) {
    if(v>100)
        v = 100
    v = v/2 + 2
    data.unshift(v)
    if(data.length>MaxDataLen) {
        data.length = MaxDataLen
    }

    draw()
}

function draw() {
    if(!ctx) {
        return
    }

    refCanvas.value.width = refCanvas.value.width
    
    ctx.moveTo(MaxDataLen+1, 51-data[0])
    for(let i=1;i<data.length;i++) {
        ctx.lineTo(MaxDataLen-i+2, 51-data[i])
    }
    ctx.strokeStyle = props.color
    ctx.stroke()
}

defineExpose({push})
</script>